//
//  SYComposeViewController.swift
//  SingWeibo
//
//  Created by shiying on 15/12/26.
//  Copyright © 2015年 shiying. All rights reserved.
//

import UIKit
import SVProgressHUD

class SYComposeViewController: UIViewController {

    private let maxTipLength = 140
    private var toolBarConstraint: NSLayoutConstraint? // 约束
    private var photoSelectorConstraint: NSLayoutConstraint? // 图片的约束
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        setupTextView()
        setupPhotoSelector()
        setupToolbar()
        setupTipLengthLabel()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        self.addChildViewController(photoSelectorVC)
        self.addChildViewController(emoticonVC)
        
    }
    // 生命周期方法
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(true)
        if photoSelectorConstraint?.constant != 0 {
            
            textView.becomeFirstResponder()
        }

    }
    
    /// 键盘的通知方法
    func willChangeFrame(notification: NSNotification) {
        
        let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval // 获取键盘时间

        let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue // 获得键盘frame 改变之后的值
        self.toolBarConstraint?.constant = -(UIScreen.mainScreen().bounds.height - frame!.origin.y)
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()

        }
    }

    func setupNav() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cencel")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
    
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()

        setupNavigationTitle()
    }
    
    // MARK: - 设置Label
    func setupTipLengthLabel() {
        view.addSubview(tipLengthLabel)
        tipLengthLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil, offset: CGPoint(x: -5, y: -5))
    
    }
    
    /// 设置图片选择器
    func setupPhotoSelector() {
        let photoSelectorView = photoSelectorVC.view
        view.addSubview(photoSelectorView)
        
        photoSelectorView.translatesAutoresizingMaskIntoConstraints = false // 去除影响
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ps]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ps" : photoSelectorView]))
    
        view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: view.frame.height * 0.6))
        
        
        photoSelectorConstraint = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: view.frame.height * 0.6)
        view.addConstraint(photoSelectorConstraint!)
    
    }
    
    // MARK: - NavigationItem 方法
    func cencel() {
        textView.resignFirstResponder() // 取消第一响应者
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func send() {
        let text = textView.emoticonText()
        // 获取图片
        let image = photoSelectorVC.photos.first
        
        if maxTipLength - text.characters.count < 0 {
            SVProgressHUD.showErrorWithStatus("文字超出范围...")
            return
        }
        
        SVProgressHUD.showWithStatus("正在加载中...")
        SYAFNTool.sharedInsetace.sendStatus(text, image: image) { (result, error) -> () in
                   if error != nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("微博发送成功...")
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.cencel()
            })
        }
    }
    
    func setupNavigationTitle() {
        let titleText = "发微博"
        
        if let name = SYUseAccount.loadUserAccount()?.screen_name {
        
            let titleName = titleText + "\n" + name
            
            let nameLabel: UILabel = UILabel()
            
            nameLabel.font = UIFont.systemFontOfSize(14)
            nameLabel.textAlignment = NSTextAlignment.Center
            nameLabel.numberOfLines = 0
            nameLabel.textColor = UIColor.blackColor()
            
            let attrName =  NSMutableAttributedString(string: titleName)
            let rangeName = (titleName as NSString).rangeOfString(name)
            
            attrName.addAttributes([NSForegroundColorAttributeName : UIColor.grayColor()], range:rangeName)
            attrName.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(11)], range: rangeName)
            
            
            nameLabel.attributedText = attrName
            
            nameLabel.sizeToFit()
            navigationItem.titleView = nameLabel

        } else {
            navigationItem.title = titleText
        
        }
        
    }
    
    // MARK: - 添加 toolbar
    func setupToolbar() {
        
        view.addSubview(toolbar)
        
        // 约束
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        toolBarConstraint = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 数组里面有字典，可以取出图片
        let itemSettings = [["imageName": "compose_toolbar_picture", "action" : "picture"],
            ["imageName": "compose_trendbutton_background", "action" : "trendbutton"],
        ["imageName": "compose_mentionbutton_background", "action" : "mentionbutton"],
        ["imageName": "compose_emoticonbutton_background", "action" : "emoticonbutton"],
        ["imageName": "compose_addbutton_background", "action" : "addbutton"]]
        
        
        
        // 创建可变item数组
        var items = [UIBarButtonItem]()
        
        // 遍历  还可以用tag
        for dict in itemSettings {
            let image = dict["imageName"]
            let action = dict["action"]
            let item = UIBarButtonItem(imageName: image!) // 设置图片
            
            let buttom = item.customView as! UIButton // 转换成按钮
            buttom.addTarget(self, action: Selector(action!), forControlEvents: UIControlEvents.TouchUpInside) // 按钮点击事件
            items.append(item) // 添加
        
            let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)  // 设置弹簧
            items.append(flexible) // 添加
        }
        items.removeLast()
        toolbar.items = items
    }
    
    func setupTextView() {
        view.addSubview(textView)
        textView.delegate = self
        textView.ff_Fill(view)
    }
    
    // MARK: - 点击事件
    func picture() {
    
        // 当图片选择器约束不是0的时候，取消键盘，弹出他
        photoSelectorConstraint?.constant = 0
        // 取消第一响应
        textView.resignFirstResponder()
        // 动画
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    func trendbutton() {
        
    }
    func mentionbutton() {
        
    }
    
    // 表情键盘
    func emoticonbutton() {
        textView.resignFirstResponder() //取消第一响应者
        
        // GCD 设置表情键盘或者默认键盘
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil;
            self.textView.becomeFirstResponder() // 第一响应者
        }
        
    }

    func addbutton() {
        
    }

    // MARK: - 懒加载
    private lazy var toolbar: UIToolbar = {
        let toolbar = UIToolbar()
        
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1)

        return toolbar
    }()
    
    private lazy var textView: SYTexeView = {
        let textView = SYTexeView()
        textView.backgroundColor = UIColor(white: 0.8, alpha: 1)
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.blackColor()
        textView.placeholder = "分享新鲜事..."
        textView.alwaysBounceVertical = false
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return textView
    }()
    
    private lazy var tipLengthLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.lightGrayColor()
  
        return label
    }()
    
    /// 表情
    private lazy var emoticonVC: SYEmoticonViewController = SYEmoticonViewController(textView: self.textView)
    
    /// 图片选择器
    private lazy var photoSelectorVC: SYPhotoSelectorController = SYPhotoSelectorController()
    
}

extension SYComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        let count = textView.emoticonText().characters.count
        let length = maxTipLength - count
        tipLengthLabel.text = String(length)
        tipLengthLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
    }

}
